<?php
use \Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use \AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use api\zhengmaotong\model\CodeModel;
use think\Db;
use api\zhengmaotong\model\WalletModel;

//检查验证码是否正确
function checkCode($mobile,$code)
{
    $data = CodeModel::where('mobile',$mobile)->find();
    if (!$data){
        return false; // error('请发送验证码');
    }
    if ($data['code'] != $code ){
        return false; // error('验证码不正确');
    }
    if (time() - $data['send_time'] > 1200000000){
        CodeModel::where('mobile',$mobile)->delete();
        return false; //error('验证码超时，请重新发送');
    }else{
        CodeModel::where('mobile',$mobile)->delete();
        return true;
    }

}
//发送验证码
function SendCode($mobile)
{
    CodeModel::where('mobile',$mobile)->delete();
    $code = mt_rand(1111, 9999);
    $config = new Config([
        // 从阿里云获取
        'accessKeyId' => config('app.aliSms.accessKeyId'),
        'accessKeySecret' => config('app.aliSms.accessKeySecret'),
    ]);

    $config->endpoint = "dysmsapi.aliyuncs.com";
    $client = new Dysmsapi($config);

    // 运行时参数超时设置，仅对使用了该运行时参数实例的请求有效
    $runtimeOptions = new RuntimeOptions();
    // true 忽略证书校验
    $runtimeOptions->ignoreSSL = true;

    $sendSmsRequest = new SendSmsRequest();
    // 手机号
    $sendSmsRequest->phoneNumbers = $mobile;
    // 签名名称
    $sendSmsRequest->signName = config('app.aliSms.signName');
    // 模板CODE
    $sendSmsRequest->templateCode =  config('app.aliSms.sms');
    // 生成随机数作为验证码
    $sendSmsRequest->templateParam = json_encode(['code' => $code]);
    try {
        $response = $client->sendSmsWithOptions($sendSmsRequest, $runtimeOptions);
    } catch (\Exception $exception) {
        halt($exception->getMessage());
    }
    $Smscode = new CodeModel();
    $Smscode->mobile = $mobile;
    $Smscode->code = $code;
    $Smscode->send_time = time();
    $Smscode->save();
    if ($response->body->code == 'OK') {
        return json([
            'code' => 1,
            'msg' => '短信发送成功',
            'data' => null
        ]);
    }else{
        return json([
            'code' => 0,
            'msg' => '短信发送失败',
            'data' => null
        ]);
    }
}


function success($msg=' ', $data=null){
    return json([
        'code'=>1,
        'msg'=>$msg,
        'data'=>$data,
    ]);
}
//统一失败返回
function error($msg=' ',$data=null){
    return json([
        'code'=>0,
        'msg'=>$msg,
        'data'=>$data,
    ]);

}
//token
function signToken($userId,$mobie){
    $data = [
        //签发人
        'iss'=>request()->domain(),
        //签发时间
        'iat'=>time(),
        //自定义数据
        'data'=>[
            'user_id'=>$userId,
            'mobile'=>$mobie
        ]
    ];
    $key = config('app.jwt_key');
    $token= \Firebase\JWT\JWT::encode($data,$key,'HS256');
    return $token;
}//增加余额
function add_money($user_id, $money, $reason, $type = 1)
{
    // 获取用户信息
    $user =\api\zhengmaotong\model\WalletModel ::name('users')->where('id', $user_id)->find();
    if (!$user) {
        throw new Exception('用户不存在');
    }

    // 计算新的余额
    //$newBalance = $user['wallet'] + $money;
    if ($type == 1){
        $newBalance = $user['wallet'] + $money;
    } elseif ($type == 0){
        $newBalance = $user['wallet'] - $money;
    } else {
        throw new Exception('无效的类型');
    }

    // 更新用户余额
    WalletModel::name('users')->where('id', $user_id)->update(['wallet' => $newBalance]);

    // 记录流水
    WalletModel::insert([
        'user_id' => $user_id,
        'money' => $money,
        'reason' => $reason,
        'before' => $user['wallet'],
        'after' => $newBalance,
        'type' => $type, // 类型：1-存储
        'create_time' => date('Y-m-d H:i:s')
    ]);

    return $newBalance;
}

function record($user_id)
{
    // 查询用户的流水记录
    $logs = WalletModel::where('user_id', $user_id)
        ->order('create_time', 'desc')
        ->select();

    if (!$logs) {
        throw new Exception('没有找到流水记录');
    }

    return $logs;
}

